#-*- encoding: utf-8 -*-
import win32com.client 
from Misc.Utils import *

from DataAccess.QueryBlp import *

from datetime import date,timedelta

from ReportTool.HldReport import *
from ReportTool.PnLReport import *
from ReportTool.NAVReport import *
from ReportTool.MktValReport import *
from ReportTool.TradeReport import *
from ReportTool.RealizedPnL import *
from ReportTool.OnshoreHldReport import *

from Config.ReportConfig import *
		
def CSFB_Daily_Trade_Report(ref_date):
	trd = query_trade(ref_date, ref_date, portf_list=['SC028'])
	
	xApp = win32com.client.Dispatch("Excel.Application")
	xBook = xApp.Workbooks.Add()
	xSht = xBook.Worksheets(1)
	
	row = 1
	for elem in trd:
	
		if elem[5] == 'PNOTE':
			blp_ticker = ch_ticker_to_blp_ticker(elem[3])
		elif (elem[5] == 'STOCK' and elem[9] == 'HKD'):
			blp_ticker = hk_ticker_to_blp_ticker(elem[3])
		else:
			blp_ticker = elem[3]
		
		sec_name = query_blp_static([blp_ticker], ['NAME'])[blp_ticker]['NAME']
		sec_info = {}
		if is_equity(blp_ticker):
			sec_info = query_blp_static([blp_ticker], ['ID_ISIN', 'ID_SEDOL1'])
		
		xSht.Cells(row, 1).Value = elem[0]
		xSht.Cells(row, 3).Value = elem[5]
		direction = ''
		if elem[6] == 'SHORT COVERING':
			direction = 'BUY'
		elif elem[6] == 'SHORT SELLING':
			direction = 'SS'
		else:
			direction = elem[6]
		xSht.Cells(row, 4).Value = direction
		pb_id = None
		if elem[5] == 'PNOTE':
			pb_id = 'CSFB'
		if elem[5] == 'STOCK':
			pb_id = 'CSHK'
		xSht.Cells(row, 5).Value = pb_id
		xSht.Cells(row, 6).Value = '0NO0' if is_equity(blp_ticker) else 'AC0125'
		xSht.Cells(row, 7).Value = 'MARGIN'
		xSht.Cells(row, 8).Value = sec_info[blp_ticker]['ID_ISIN'] if sec_info.has_key(blp_ticker) else None
		xSht.Cells(row, 9).Value = sec_info[blp_ticker]['ID_SEDOL1'] if sec_info.has_key(blp_ticker) else None
		xSht.Cells(row, 12).Value = blp_ticker
		xSht.Cells(row, 13).Value = elem[9]
		xSht.Cells(row, 14).Value = elem[9]
		xSht.Cells(row, 15).Value = 1
		xSht.Cells(row, 18).Value = elem[7]
		xSht.Cells(row, 19).Value = elem[8]
		xSht.Cells(row, 21).Value = elem[7]*elem[8]
		xSht.Cells(row, 27).Value = elem[7]*elem[8]
		xSht.Cells(row, 28).Value = elem[8]
		xSht.Cells(row, 30).Value = elem[7]*elem[8]
		xSht.Cells(row, 36).Value = elem[7]*elem[8]
		xSht.Cells(row, 37).Value = elem[1].strftime("%Y%m%d") if isinstance(elem[1], date) else None
		xSht.Cells(row, 38).Value = elem[10].strftime("%Y%m%d") if isinstance(elem[10], date) else None
		xSht.Cells(row, 45).Value = sec_name	
		row += 1
	
	rept_file = REPT_PATH + 'springscapital_creditsuisse.''' + ref_date.strftime("%Y%m%d") + '.csv'
	xBook.SaveAs(rept_file, win32com.client.constants.xlCSV)
	xBook.Close()
	del xApp
	
	print 'info, cs daily trade report completed at ', ref_date.isoformat()